package authentication.authenticator;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DatabaseAuthenticator implements Authenticator
{
	private final String dbLocation;
	private final String dbUsername;
	private final String dbPassword;
	
	
	public DatabaseAuthenticator(String dbLocation, String dbUsername, String dbPassword)
	{
		this.dbLocation = dbLocation;
		this.dbUsername = dbUsername;
		this.dbPassword = dbPassword;
	}

	@Override
	public AuthenticationResult authenticate(String username, String password)
	{
		AuthenticationResult result = null;
		java.sql.Connection dbConnection = null;
		
		try
		{
			dbConnection = DriverManager.getConnection(dbLocation, dbUsername, dbPassword);
		}
		catch (SQLException e) 
		{ 
			result = AuthenticationResult.FailedToConnectToDatabase;
			e.printStackTrace(); 
		}
		
		if (dbConnection != null)
		{
			try
			{
				Statement statement = dbConnection.createStatement();
				
				statement.execute("SELECT COUNT(*) FROM users WHERE username='" + username + "' AND password='" + password + "'");
				
				ResultSet results = statement.getResultSet();
				
				results.next();
				
				result = results.getInt(1) != 0 ? AuthenticationResult.Success : AuthenticationResult.InvalidCredentials;
			}
			catch (SQLException e) { e.printStackTrace(); }
			
			try
			{
				dbConnection.close();
			}
			catch (SQLException e) { e.printStackTrace(); }
		}
		
		return result;
	}
}
